//
//  RESTClient.m
//  storeapp
//
//  Created by huangyi on 13-3-12.
//  Copyright (c) 2013年 ios. All rights reserved.
//

#import "RESTClient.h"
#import "toolbox.h"

@interface RESTClient ()

@end

@implementation RESTClient

+(NSString*)fullURL:(NSString*)urlstr{
    AppController *app=[AppController shared];
    NSString *ip=app.config[@"address"];
    NSString *server=[NSString concatStrings:@"http://",ip, nil];
    if (![urlstr hasPrefix:@"/"]) {
        urlstr=[NSString concatStrings:@"/",urlstr, nil];
    }
    urlstr=[urlstr stringByReplacingOccurrencesOfString:@"//" withString:@"/"];
    urlstr=urlstr.urlencode;
    return [server stringByAppendingString:urlstr];
}

+(RESTClient*)syncRequest:(NSString*)method withAPI:(NSString*)format,...{
    NSString *urlstr=nil;
	va_list args;
	if (format)
	{
		va_start(args, format);
        urlstr=[[NSString alloc] initWithFormat:format arguments:args];
		va_end(args);
	}
    RESTClient *client=[[RESTClient alloc] init];
    NSString *fullstring=[RESTClient fullURL:urlstr];
    AppController *app=[AppController shared];
    NSNumber *loginid=app.session[@"loginid"];
    NSNumber *role=app.session[@"role"];
    if (loginid!=nil) {
        if ([fullstring contains:@"?"]) {
            fullstring=[NSString concatStrings:fullstring,@"&loginid=",loginid.stringValue,@"&role=",role.stringValue, nil];
        }else{
            fullstring=[NSString concatStrings:fullstring,@"?loginid=",loginid.stringValue,@"&role=",role.stringValue, nil];
        }
    }
    NSURL *url=[NSURL URLWithString:fullstring];
    NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:url];
    request.HTTPMethod=method;
    NSHTTPURLResponse *response=nil;
    NSError *error=nil;
    NSData *result=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
    if (error) {
        client.code=-1;
        client.message=error.localizedDescription;
    }else{
        if (response.statusCode==200) {
            client.head=[response allHeaderFields];
            if (result.isValidJSON) {
                NSDictionary *json=result.jsonObject;
                NSNumber *code=json[@"code"];
                if (code.intValue==0) {
                    client.code=0;
                    client.message=json[@"message"];
                    client.json=json[@"result"];
                    if (client.json==nil) {
                        client.json=json;
                    }
                }else{
                    client.code=code.intValue;
                    client.message=json[@"error"];
                }
            }else{
                client.code=0;
                client.message=result.fingerprint;
                client.data=result;
            }
        }else{
            client.code=-1;
            NSDictionary *head=[response allHeaderFields];
            client.head=head;
            NSString *message=head[@"err_msg"];
            message=message.base64decode.stringValue;
            if (message==nil) {
                message=[NSHTTPURLResponse localizedStringForStatusCode:response.statusCode];
            }
            client.message=message;
        }
    }
    NSArray *log=[NSArray arrayWithObjects:@"JSON",fullstring,@(client.code),client.message,client.json, nil];
    DDLogCVerbose(@"%@",log);
    return client;
}

+(RESTClient*)HEAD:(NSString*)format,...{
    NSString *urlstr=nil;
	va_list args;
	if (format)
	{
		va_start(args, format);
        urlstr=[[NSString alloc] initWithFormat:format arguments:args];
		va_end(args);
	}
    NSString *rest=[NSString concatStrings:@"/servlets/binserv/p/",urlstr, nil];
    return [RESTClient syncRequest:@"HEAD" withAPI:rest];
}

+(RESTClient*)POST:(NSString*)format,...{
    NSString *urlstr=nil;
	va_list args;
	if (format)
	{
		va_start(args, format);
        urlstr=[[NSString alloc] initWithFormat:format arguments:args];
		va_end(args);
	}
    NSString *rest=[NSString concatStrings:@"/servlets/binserv/p/",urlstr, nil];
    return [RESTClient syncRequest:@"POST" withAPI:rest];
}


+(RESTClient*)JSON:(NSString*)data SEND:(NSString*)format,...{
    NSString *urlstr=nil;
	va_list args;
	if (format)
	{
		va_start(args, format);
        urlstr=[[NSString alloc] initWithFormat:format arguments:args];
		va_end(args);
	}
    RESTClient *client=[[RESTClient alloc] init];
    NSString *rest=[NSString concatStrings:@"/servlets/binserv/p/",urlstr, nil];
    NSString *fullstring=[RESTClient fullURL:rest];
    AppController *app=[AppController shared];
    NSNumber *loginid=app.session[@"loginid"];
    NSNumber *role=app.session[@"role"];
    if (loginid!=nil) {
        if ([fullstring contains:@"?"]) {
            fullstring=[NSString concatStrings:fullstring,@"&loginid=",loginid.stringValue,@"&role=",role.stringValue, nil];
        }else{
            fullstring=[NSString concatStrings:fullstring,@"?loginid=",loginid.stringValue,@"&role=",role.stringValue, nil];
        }
    }
    NSURL *url=[NSURL URLWithString:fullstring];
    NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:url];
    request.HTTPMethod=@"POST";
    data=[NSString concatStrings:@"json=",data, nil];
    request.HTTPBody=data.dataValue;
    NSHTTPURLResponse *response=nil;
    NSError *error=nil;
    NSData *result=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
    if (error) {
        client.code=-1;
        client.message=error.localizedDescription;
    }else{
        if (response.statusCode==200) {
            client.head=[response allHeaderFields];
            if (result.isValidJSON) {
                NSDictionary *json=result.jsonObject;
                NSNumber *code=json[@"code"];
                if (code.intValue==0) {
                    client.code=0;
                    client.message=json[@"message"];
                    client.json=json[@"result"];
                    if (client.json==nil) {
                        client.json=json;
                    }
                }else{
                    client.code=code.intValue;
                    client.message=json[@"error"];
                }
            }else{
                client.code=0;
                client.message=result.fingerprint;
                client.data=result;
            }
        }else{
            client.code=-1;
            NSDictionary *head=[response allHeaderFields];
            client.head=head;
            NSString *message=head[@"err_msg"];
            message=message.base64decode.stringValue;
            if (message==nil) {
                message=[NSHTTPURLResponse localizedStringForStatusCode:response.statusCode];
            }
            client.message=message;
        }
    }
    NSArray *log=[NSArray arrayWithObjects:@"JSON",fullstring,@(client.code),client.message,client.json, nil];
    DDLogCVerbose(@"%@",log);
    return client;
}


@end
